<template>
	<view class="order-details" v-show="options.orderId">
		<view class="order-no">订单编号: {{options.orderId}}</view>
		<view class="tips-success" v-if="options._state == 2">预订成功</view>
		<view class="tips-success" v-if="options._state == 14">已完成</view>
		<view class="tips-success" v-if="options._state == 31">退款中</view>
		<view class="tips-success" v-if="options._state == 99">已使用</view>
		<view class="tips-success" v-if="options._state == 11">待使用</view>
		<view class="tips-success" v-if="options._state == 32">已退款</view>
		<!-- 提示 -->
		<view class="pay-tips" v-if="options._state == 10">
			<view class="pay-tips-block">
				<view class="pay-tips-text">
					<text class="pay-tips-text1">待支付</text>
					<text class="pay-tips-text2">剩余时间：{{times}}</text>
				</view>
				<view class="pay-tips-text3">库存有限，请尽快完成付款，过时将自动取消</view>
			</view>
			<view class="pay-btn" @click="handlePay">去支付</view>
		</view>

		<!-- 预定信息 待付款 -->
		<view class="book-info" v-if="options._state == 10" style="margin-bottom: 40rpx;">
			<view class="title">预订信息</view>
			<view class="book-info-block">
				<view class="book-info-view">在线支付</view>
				<text>￥{{options.payPrice}}</text>
				<text class="btn" @click="handleAlert(1)">明细</text>
			</view>
			<view class="book-info-block" style="margin: 15rpx 0;">
				<view class="book-info-view">游客信息</view>
				<text v-for="(item,index) in people4" :key="index">{{item}}</text>
				<text class="btn" @click="handleAlert(2)">详情</text>
			</view>
			<view class="book-info-block">
				<view class="book-info-view">联系人</view>
				<text>{{options.userName}}</text>
				<text>{{options.userPhone}}</text>
			</view>
		</view>

		<!-- 列表 -->
		<view class="list">
			<view class="list-item" v-for="(item,index) in options.dateils" :key="index">
				<view class="title">
					<text>{{item.proName}} X{{item.proCount}}</text>
					<text style="font-size: 28rpx; color: #D9001B;margin-left: 60rpx;" v-if="getText(item,1)">{{getText(item,2)}}</text>
				</view>
				<view class="text">
					<text>使用时间</text>
					<text class="text-color">{{item.proDate}}</text>
				</view>
				<view class="text">
					<text>入园时间</text>
					<text class="text-color">{{item.enterTime}}</text>
				</view>
				<view class="text">
					<text>入园地址</text>
					<text class="text-color">{{item.enterAddress}}</text>
				</view>
				<!-- 二维码 -->
				<view class="qr-box">
					<view class="qr-box-title">凭二维码直接入园</view>
					<view class="qr-box-code">兑换码：{{item.eCode || ''}}</view>
					
					<image :src="item.tempFilePath" class="qr" v-if="item.tempFilePath && !showQrTips" mode=""></image>
					<canvas style="width: 150px;height: 150px;margin: 15rpx 0;" v-else-if="!showQrTips" :canvas-id="'canvas-' + index" />
					
					<view class="qr" v-if="showQrTips">
						<view class="qr-cell-1">订单支付成功后,</view>
						<view class="qr-cell-2">生成入园二维码</view>
					</view>
					
					<view class="qr-box-tips" v-if="item.proName.indexOf('年卡') != -1">
						注：此卡仅限本人使用，需实名制认证，不得转借他人，自购买之日起30天内凭兑换码，携带身份证到景区售票处换实体卡，并采集人像激活使用。此卡自购买之日起30天内到景区售票处激活有效，超过30天未激活，请您退款重新购买。此卡仅限登塔使用。
					</view>
				</view>
			</view>
		</view>

		<!-- 预定信息 待使用 -->
		<view class="book-info" v-if="options._state != 10">
			<view class="title">预订信息</view>
			<view class="book-info-block">
				<view class="book-info-view">在线支付</view>
				<text>￥{{options.payPrice}}</text>
				<text class="btn" @click="handleAlert(1)">明细</text>
			</view>
			<view class="book-info-block" style="margin: 15rpx 0;">
				<view class="book-info-view">游客信息</view>
				<text v-for="(item,index) in people4" :key="index">{{item}}</text>
				<text class="btn" @click="handleAlert(2)">详情</text>
			</view>
			<view class="book-info-block">
				<view class="book-info-view">联系人</view>
				<text>{{options.userName}}</text>
				<text>{{options.userPhone}}</text>
			</view>
		</view>

		<!-- 按钮 -->
		<view class="order-details-btn">
			<view class="button1" @click="handleDelOrder" v-if="options._state == 10 || options._state == 2">取消订单</view>
			<view class="button1" @click="handleCancelVote" v-if="options._state == 2 || options._state == 11 || options._state == 99">申请退票</view>
			<view class="button2" @click="handleAgain">再次预订</view>
		</view>

		<!-- 弹框显示 -->
		<orde-details-tips ref="orde-details-tips"></orde-details-tips>
		<cancel-vote-reason ref="cancel-vote-reason" @submit="goOrder"></cancel-vote-reason>
	</view>
</template>
<script>
	import ordeDetailsTips from "./components/ordeDetailsTips.vue";
	import CancelVoteReason from '@/components/cancelVoteReason';
	import drawQrcode from '@/utils/weapp.qrcode.min.js';
	// orderType:  TICKET中塔  HOTEL门票
	import {
		getOrderByIdDetails,
		cancelTicOrder,
		getDetailListByOrderNumMobile,
		refundOfOrder
	} from "@/http";
	import {
		dateFormat,
		beginEndtime
	} from "@/utils/pay";
	export default {
		name: "OrderDetails",
		components: {
			ordeDetailsTips,
			CancelVoteReason
		},
		data() {
			return {
				name: "",
				time: null, //需要循环
				times: '2:00:00',
				showQrTips: false,
				options: {}
			}
		},
		onLoad() {
			this.getList();
		},
		methods: {
			getList() {
				this.options = uni.getStorageSync('echo_details');
				uni.setStorageSync('echo_details', '');
				this.$nextTick(()=>{
						console.log('订单参数：', this.options)
						this.getTimeHHMMSS();
						let arr = [14, 31, 99, 11, 2,32]
						if (arr.some(item => item == this.options._state)) { //加载二维码
							uni.showLoading({title: ' '});
							let peoArr = this.options.dateils.map((item, index) => {
								return new Promise((reslove, reject) => {
									drawQrcode({
										x: 0,
										y: 0,
										padding: 10,
										width: 150,
										height: 150,
										canvasId: `canvas-${index}`,
										typeNumber: -1, //最大27
										text: item.eCode,
										background: '#FFFFFF', //二维码背景颜色，默认值白色
										foreground: '#000000', //二维码前景色，默认值黑色
										callback(e) {
											setTimeout(() => { //转成图片
												wx.canvasToTempFilePath({
													x: 0,
													y: 0,
													width: 150,
													height: 150,
													canvasId: `canvas-${index}`,
													success: (res) => {
														item.tempFilePath = res.tempFilePath;
														reslove(item);
													}
												});
											}, 50);
										}
									});
								})
							});
							Promise.all(peoArr).then(res => {
								this.options.dateils = res;
								uni.hideLoading();
							});
						}else{
							this.showQrTips = true;
						}
				})
			},
			handleCancelVote() {
				this.$nextTick(() => {
					let options = JSON.parse(JSON.stringify(this.options));
					options.eCodeList = options.dateils.map(item => item.eCode);
					options.orderNum = options.orderId;
					this.$refs['cancel-vote-reason'].init(options);
				})
			},
			goOrder() {
				uni.redirectTo({
					url: '/myPages/myOrder/index?current=0'
				});
			},
			handleAlert(state) {
				this.$nextTick(() => {
					this.$refs['orde-details-tips'].init(state, this.options.dateils);
				})
			},
			handlePay() { //支付
				let totalPrice = 0;
				this.weixinPay(this.options.payPrice, this.options.orderId, this.options)
			},
			handleAgain() {
				uni.setStorageSync('echo_details', this.options.dateils);
				uni.navigateTo({ //再次预约
					url: `/homePages/scenicSpot/reserve?data=${JSON.stringify({
						productName: this.options.dateils[0].proName,
						productId: this.options.dateils[0].productId,
						productIsTheatre: this.options.dateils[0].productIsTheatre,
						productNum: this.options.dateils[0].proCount,
						productPrice: this.options.dateils[0].proPrice,
						userName:this.options.userName,
						userPhone:this.options.userPhone,
						orderId: this.options.orderNum,
						payPrice: this.options.totalPrice,
						totalNum:this.options.totalNum,
						storeOrderId: this.options.storeOrderId,
						goodsId:this.options.storeOrderId,
						productCode:this.options.dateils[0].proCode
					})}&date=${this.options.dateils[0].proDate}`
				});
			},
			async handleDelOrder() { //取消订单
				uni.showLoading({
					title: '正在取消订单'
				});
				let res = await cancelTicOrder({
					storeOrderId: this.options.storeOrderId
				})
				uni.showToast({
					title: '操作成功',
					icon: 'success',
					mask: true
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 800);
			},
			getTimeHHMMSS() {
				if (this.options._state != 10) {
					clearInterval(this.time);
					this.time = null;
					return;
				}
				let s = new Date(this.options.createTime.replace(/\-/g, "\/"));
				s.setHours(s.getHours() + 2);
				s = s.getTime();
				this.times = beginEndtime(Date.now(), s);
				this.time = setInterval(() => { //计算时间
					if (s <= Date.now()) {
						clearInterval(this.time);
						this.times = "此订单已取消";
						this.time = null;
						uni.navigateBack(); //退出去
					} else {
						this.times = beginEndtime(Date.now(), s);
					}
				}, 1000);
			},
			async handleCancelOrder() { //退订
				try {
					uni.showLoading({
						title: "正在退订..."
					});
					let res = await refundOfOrder({
						eCodeList: this.options.dateils.map(item => item.eCode),
						orderNum: this.options.orderId,
						userName: this.options.userName,
						userPhone: this.options.userPhone
					});
					uni.showToast({
						title: "退订成功",
						icon: "success",
						mask: true
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 800);
				} catch (err) {
					uni.hideLoading();
				};
			},
			async weixinPay(totalPrice, orderId, options) {
				let that = this;
				this.$http.getTicketOrderPay({
					payAmount: totalPrice + '',
					thirdOrderId: orderId,
					thirdType: '3',
					payPattern: '1'
				}).then(res => {
					uni.hideLoading();
					let codelist = res.data.weChatPayDTO;
					uni.requestPayment({
						provider: 'wxpay', //
						timeStamp: codelist.timeStamp,
						nonceStr: codelist.nonceStr,
						package: codelist.packageStr,
						signType: 'MD5', //不可变
						paySign: codelist.paySign,
						success: function(res) {
							uni.showToast({
								title: '支付成功！',
								icon: 'success'
							});
							that.$http.setTicketPaySuccess({
								thirdOrderId: orderId,
								thirdType: '3',
								wxPayType: '2'
							}).then(async res => {
								let _res = await getOrderByIdDetails({
									storeOrderId: options.storeOrderId,
									orderType: options.orderType
								});
								that.options.dateils = _res.data.data;
								that.options._state = 2; //变成待支付
								uni.setStorageSync('echo_details', that.options);
								that.getList();
							});
						},
						fail: function(err) {
							console.log(err);
						}
					});
				})
			},
			handleCancel() {
				this.show = false;
				this.value1 = '';
			},
			getText(options,numb){
				let str = '';
				let  writeOffNum = options.writeOffNum // 已核销
				let  refunding = options.proCount - writeOffNum; //退款中
				if(writeOffNum>0){
					str = `${str}已核销 x ${writeOffNum}`
				}

				if(Number(options.orderStatus) == 31 && refunding>0) str = `${str} 退款中 x ${refunding}`;
				if(Number(options.orderStatus) == 32 && refunding>0) str = `${str} 已退款 x ${refunding}`;
				
				if(str) return `( ${str} )`;
				return false;
				
			}
		},
		onHide() {
			clearInterval(this.time)
			this.time = null
		},
		computed: {
			people4() {
				let arr = [];
				if (this.options && this.options.dateils) {
					this.options.dateils.forEach(i => {
						i.visitorList.forEach(o => {
							if (arr.length < 4) arr.push(o.name);
						});
					});
				};
				return arr;
			}
		}
	}
</script>
<style lang="scss" scoped>
	$padding: 30rpx;

	.tips-success {
		font-size: 32rpx;
		font-weight: bold;
		padding: 0 $padding;
		color: rgba(245, 154, 35, 1);
		margin-bottom: 8rpx;
	}

	.order-details {
		.order-details-btn {
			display: flex;
			align-items: center;
			justify-content: center;

			.button1,
			.button2 {
				background-color: #ffffff;
				width: 280rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				border-radius: 14rpx;
				border: 1px solid #333333;
				color: #333333;
				font-size: 32rpx;
				margin: 60rpx 0;
			}

			.button1 {
				margin-right: 70rpx;
			}
		}

		.list {
			.list-item {
				padding: 0 $padding 40rpx $padding;
				background-color: #ffffff;

				&+.list-item {
					margin-top: 40rpx;
				}

				.qr-box {
					display: flex;
					align-items: center;
					justify-content: center;
					flex-direction: column;
					margin-top: 80rpx;

					.qr-box-title {
						font-weight: bold;
						font-size: 28rpx;
					}

					.qr-box-code {
						color: #666666;
						font-size: 24rpx;
						margin-top: 10rpx;
					}

					.qr {
						width: 300rpx;
						height: 300rpx;
						margin: 15rpx 0;
						border: 1rpx solid #f2f2f2;
						display: flex;
						align-items: center;
						justify-content: center;
						flex-direction: column;
						font-size: 30rpx;
						color: #333333;
						.qr-cell-2{
							margin-top: 20rpx;
						}
					}

					.qr-box-tips {
						width: 600rpx;
						color: #666666;
						font-size: 24rpx;
						line-height: 36rpx;
					}
				}

				.text {
					margin-bottom: 10rpx;
					display: flex;
					align-items: center;

					.text-color {
						color: rgba(245, 154, 35, 1);
						margin-left: 60rpx;
						font-size: 26rpx;
					}
				}

				.title {
					font-weight: bold;
					font-size: 32rpx;
					padding: 30rpx 0 20rpx 0;
				}
			}
		}

		.book-info {
			padding: 20rpx $padding;
			background-color: #ffffff;

			.book-info-block {
				position: relative;
				display: flex;
				font-size: 28rpx;

				.book-info-view {
					width: 130rpx;
				}

				text {
					margin-left: 40rpx;
				}

				.btn {
					position: absolute;
					right: 0;
					top: 50%;
					transform: translate(0, -50%);
					color: #0000FF;
				}
			}

			.title {
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 20rpx;
				color: #333333;
			}
		}

		.pay-tips {
			display: flex;
			align-items: center;
			justify-content: space-between;
			background-color: #ffffff;
			padding: 20rpx $padding;

			.pay-tips-block {
				.pay-tips-text {
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;
				}

				.pay-tips-text1 {
					color: rgba(245, 154, 35, 1);
					font-size: 32rpx;
					margin-right: 20rpx;
				}

				.pay-tips-text2,
				.pay-tips-text3 {
					font-size: 24rpx;
					color: #333333;
				}
			}

			.pay-btn {
				width: 154rpx;
				height: 68rpx;
				line-height: 68rpx;
				background-color: rgba(245, 154, 35, 1);
				border-radius: 8rpx;
				font-size: 28rpx;
				color: #ffffff;
				text-align: center;
			}
		}

		.book-info {
			margin-top: 40rpx;
		}

		.order-no {
			padding: $padding;
		}

		&::after {
			content: "";
			position: fixed;
			z-index: -999;
			top: 0;
			right: 0;
			left: 0;
			bottom: 0;
			background-color: #f2f2f2;
		}
	}
</style>
